package javawdw.io.zip;

import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;

public class ExtractGoal implements Goal {
	private Zip zip;
	private File desDir;

	public ExtractGoal(File desDir) {
		this.desDir = desDir;
	}

	public void visit(Zip zip) {
		this.zip = zip;
	}

	public void visit(ZipElement element) {
		try {
			String name = element.getName();
			if (!name.endsWith(File.separator)) {
				File file = new File(desDir, name);
				File parent = file.getParentFile();
				if (!parent.exists()) {
					parent.mkdirs();
				}
				InputStream in = zip.getInputStream(element);
				InputStream bis = new BufferedInputStream(in);
				OutputStream out = new FileOutputStream(file);
				OutputStream os = new BufferedOutputStream(out);
				byte[] temp = new byte[8192];
				int index = -1;
				while ((index = bis.read(temp)) != -1) {
					os.write(temp, 0, index);
				}
				bis.close();
				in.close();
				os.close();
				out.close();
			}
		} catch (FileNotFoundException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}
	}
}